<template>
  <ContentWrap v-loading="formLoading">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <!-- <el-form-item label="用户id" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入用户id" />
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        &lt;!&ndash; <el-input v-model="formData.areaName" placeholder="请输入区域名称" /> &ndash;&gt;
        <el-cascader v-model="formData.areaId" :options="categoryList"
          :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }" class="w-1/1" clearable
          filterable popper-class='cascader' placeholder="请选择区域" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item label="信息类型" prop="supplyTypeId">
        <el-cascader v-model="formData.supplyTypeId" :options="supplyList"
          :props="{ value: 'id', label: 'typeName', children: 'children', checkStrictly: true }" class="w-1/1"
          popper-class='cascader' clearable filterable placeholder="请选择信息类型" @change="supplyTypeChange" />
      </el-form-item>
      <el-form-item label="酒类名称" prop="infoName">
        <el-input v-model="formData.infoName" placeholder="请输入信息名称" />
      </el-form-item>
      <el-form-item label="发布类型" prop="infoType">
        <el-select v-model="formData.infoType" placeholder="请选择发布类型">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SUPPLUY_TYPE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="子品类" prop="infoTitle">
        <el-input v-model="formData.infoTitle" placeholder="请输入简短标题" />
      </el-form-item>
      <el-form-item label="统计使用" prop="countName">
        <el-input v-model="formData.countName" placeholder="请输入统计标题" />
      </el-form-item>
      <el-row>
        <el-col :span="6">
          <el-form-item label="多少瓶" prop="quantity">
            <el-input-number v-model="formData.quantity" :min="0" placeholder="请输入多少瓶" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="多少件" prop="packages">
            <el-input-number v-model="formData.packages" :min="0" placeholder="请输入多少件" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="市场价" prop="marketPrice">
            <el-input-number v-model="formData.marketPrice" :min="0" placeholder="请输入市场价格" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="销售价" prop="salePrice">
            <el-input-number v-model="formData.salePrice" :min="0" placeholder="请输入销售价格" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="浏览量" prop="viewCount">
            <el-input-number v-model="formData.viewCount" :min="0" placeholder="请输入真实浏览数量" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="显示量" prop="showCount">
            <el-input-number v-model="formData.showCount" :min="0" placeholder="请输入显示浏览数量" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排 序" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" placeholder="请输入排序" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          &nbsp;
        </el-col>
      </el-row>

      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="单图" prop="image">
            <UploadImg v-model="formData.image" />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="多图" prop="imagesArr">
            <UploadImgs v-model="formData.imagesArr" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="条款" prop="clause">
        <el-input v-model="formData.clause" placeholder="请输入条款" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input type="textarea" v-model="formData.description" placeholder="请输入描述" height="300px" :rows="10" />
      </el-form-item>
      <el-form-item label="交易状态" prop="tradeStatus">
        <el-radio-group v-model="formData.tradeStatus">
          <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_STATUS)" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="特殊标签" prop="tags">
        <el-select multiple v-model="formData.tags" placeholder="请选择标签">
          <el-option v-for="dict in tagsOption" :key="dict.label" :label="dict.label" :value="dict.label" />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="6">
          <el-form-item label="担责" prop="isDuty">
            <el-radio-group v-model="formData.isDuty">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.IS_NO)" :key="dict.value" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="置顶" prop="isTop">
            <el-radio-group v-model="formData.isTop">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.IS_NO)" :key="dict.value" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="热门" prop="isHot">
            <el-radio-group v-model="formData.isHot">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.IS_NO)" :key="dict.value" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="推荐" prop="isRecommend">
            <el-radio-group v-model="formData.isRecommend">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.IS_NO)" :key="dict.value" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="保费比例" prop="premiumRatio">
            <el-input-number v-model="formData.premiumRatio" :precision="0" placeholder="请输入保费比例" clearable :min="0"
              :max="100" class="!w-240px" @input="validateInput" />&nbsp;&nbsp;&nbsp;%
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="佣金比例" prop="ratio">
            <el-input-number v-model="formData.ratio" :precision="0" placeholder="请输入佣金比例" clearable :min="0" :max="100"
              class="!w-240px" @input="validateRatioInput" />&nbsp;&nbsp;&nbsp;%
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider border-style="dashed">类型选项配置（以下选项在 酒类管理->供求信息模块->酒类类型管理 中配置）</el-divider>

      <el-form-item label="年份" prop="showYear">
        <el-select v-model="formData.showYear" placeholder="请选择年份">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YEAR)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="香型" prop="fragranceType">
        <el-select v-model="formData.fragranceType" placeholder="请选择香型">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ODOR_TYPE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="度数" prop="degree">
        <el-select v-model="formData.degree" placeholder="请选择度数">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.DEGREE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="容量" prop="capacity">
        <el-select v-model="formData.capacity" placeholder="请选择容量">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.CAPACITY)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="包装" prop="packing">
        <el-select v-model="formData.packing" placeholder="请选择包装">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.PACKING)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="产地" prop="productArea">
        <el-select v-model="formData.productArea" placeholder="请选择产地">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCING_AREA)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="标签" prop="labels">
        <el-select multiple v-model="formData.labels" placeholder="请选择标签">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SUPPLY_AND_DEMAND_LABEL)" :key="dict.label"
            :label="dict.label" :value="dict.label" />
        </el-select>
      </el-form-item>

      <el-form-item label="单位" prop="unit">
        <el-select v-model="formData.unit" placeholder="请选择单位">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.UNIT)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="语言" prop="languages">
        <el-select multiple v-model="formData.languages">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.LANGUAGE) " :key="dict.label" :label="dict.label"
            :value="dict.label" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-form>
      <el-form-item style="float: right">
        <el-button :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<script setup lang="ts">
import { SupplyInfoApi, SupplyInfoVO } from '@/api/wine/supplyinfo'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
// import { defaultProps } from '@/utils/tree'
import { handleTree } from '@/utils/tree'

/** 供求信息 表单 */
defineOptions({ name: 'SupplyInfoForm' })
const { push, currentRoute } = useRouter() // 路由
const { params } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  userId: undefined,
  infoType: undefined,
  supplyTypeId: undefined,
  infoName: undefined,
  infoTitle: undefined,
  showYear: undefined,
  areaId: undefined,
  fragranceType: undefined,
  degree: undefined,
  capacity: undefined,
  packing: undefined,
  productArea: undefined,
  areaName: undefined,
  quantity: 1,
  packages: 1,
  languages: undefined,
  countName: undefined,
  labels: [],
  tags: [],
  image: '',
  images: '',
  imagesArr: [],
  unit: undefined,
  marketPrice: 0,
  salePrice: 0,
  description: undefined,
  status: 0,
  tradeStatus: 1,
  isDuty: 1,
  viewCount: 0,
  showCount: 0,
  clause: undefined,
  sort: 0,
  isTop: 2,
  isHot: 2,
  isRecommend: 2,
  ratio: 0,
  premiumRatio: 0
})
const formRules = reactive({
  supplyTypeId: [{ required: true, message: '信息类型不能为空', trigger: 'blur' }],
  infoName: [{ required: true, message: '信息名称不能为空', trigger: 'blur' }],
  infoType: [{ required: true, message: '发布类型不能为空', trigger: 'change' }],
  infoTitle: [{ required: true, message: '简短标题不能为空', trigger: 'blur' }],
  // showYear: [{ required: true, message: '年份不能为空', trigger: 'change' }],
  // fragranceType: [{ required: true, message: '香型不能为空', trigger: 'change' }],
  // degree: [{ required: true, message: '度数不能为空', trigger: 'change' }],
  // capacity: [{ required: true, message: '容量不能为空', trigger: 'change' }],
  // packing: [{ required: true, message: '包装不能为空', trigger: 'change' }],
  // productArea: [{ required: true, message: '产地不能为空', trigger: 'blur' }],
  // areaId: [{ required: true, message: '区域不能为空', trigger: 'change' }],
  // quantity: [{ required: true, message: '多少瓶不能为空', trigger: 'blur' }],
  // packages: [{ required: true, message: '多少件不能为空', trigger: 'blur' }],
  // labels: [{ required: true, message: '标签不能为空', trigger: 'change' }],
  // tags: [{ required: true, message: '特殊标签不能为空', trigger: 'change' }],
  //unit: [{ required: true, message: '单位不能为空', trigger: 'change' }],
  marketPrice: [{ required: true, message: '市场价格不能为空', trigger: 'blur' }],
  salePrice: [{ required: true, message: '销售价格不能为空', trigger: 'blur' }],

  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const validateRatioInput = (it) => {
  console.log("value", it);
  it = it + ''.replace(/[^0-9]/g, "");
  if (it.indexOf(0) == 0) {
    it = 0;
  }
  formData.value.ratio = parseInt(it);
}

const validateInput = (it) => {
  console.log("value", it);
  it = it + ''.replace(/[^0-9]/g, "");
  if (it.indexOf(0) == 0) {
    it = 0;
  }
  formData.value.premiumRatio = parseInt(it);
}
/** 打开弹窗 */
const getDetail = async () => {
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let data = await SupplyInfoApi.getSupplyInfo(id)

      data.imagesArr = data.images ? data.images.split(',') : []

      data.labels = data.labels ? data.labels.split(',') : []
      data.tags = data.tags ? data.tags.split(',') : []
      data.editor = data.editor ? data.editor : ''
      data.description = data.description ? data.description : ''
      if (data.isTop == 0) {
        data.isTop = 2;
      }
      if (data.isHot == 0) {
        data.isHot = 2;
      }
      if (data.isRecommend == 0) {
        data.isRecommend = 2;
      }

      formData.value = data

    } finally {
      formLoading.value = false
    }
  }
}
const categoryList = ref() // 分类树
let supplyList = ref() // 分类树

onMounted(async () => {
  await initTagsOption()
  // 获得分类树
  const data = await SupplyInfoApi.getCategoryList({})
  categoryList.value = data

  // 获得分类树
  const supply = await SupplyInfoApi.typeList({})
  supplyList.value = handleTree(supply)
  await getDetail()

})
const id = params.id as unknown as number
interface ListItem {
  value: number
  label: string
}
const tagsOption = ref<ListItem[]>([])
const initTagsOption = async () => {
  const data = await SupplyInfoApi.labelList({})
  tagsOption.value = []
  data.map((item) => {
    tagsOption.value.push({
      label: item.labelName,
      value: item.id
    })
  })
}

const supplyTypeChange = (node) => {
  if (node) {
    formData.value.supplyTypeId = node[node?.length - 1]
  }
}
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'SupplyInfo' })
}


const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.imagesArr && Array.isArray(formData.value.imagesArr)) {
      formData.value.images = formData.value.imagesArr.join(',')
    } else {
      formData.value.images = ''
    }

    if (formData.value.labels && Array.isArray(formData.value.labels)) {
      formData.value.labels = formData.value.labels.join(',')
    } else {
      formData.value.labels = []

    }

    if (formData.value.tags && Array.isArray(formData.value.tags)) {
      formData.value.tags = formData.value.tags.join(',')
    } else {
      formData.value.tags = []
    }
    if (formData.value.areaId && Array.isArray(formData.value.areaId)) {
      formData.value.areaId = formData.value.areaId[formData.value.areaId.length - 1]
    } else {
      formData.value.areaId = ''
    }

    const data = formData.value as unknown as SupplyInfoVO
    if (!id) {
      await SupplyInfoApi.createSupplyInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await SupplyInfoApi.updateSupplyInfo(data)
      message.success(t('common.updateSuccess'))
    }
    close()
    dialogVisible.value = false
    // 发送操作成功的事件
  } finally {
    formLoading.value = false
  }
}

</script>
<style>
.cascader .el-radio__inner {
  top: -18px;
  left: -19px;
  border-radius: 0;
  border: 0;
  width: 170px;
  height: 34px;
  background-color: transparent;
  cursor: pointer;
  box-sizing: border-box;
  position: absolute;
}

.cascader .el-radio__input.is-checked .el-radio__inner {
  background: transparent;
}
</style>
